package com.xiaobawang.hundouluo.fragment;


import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

import androidx.fragment.app.Fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.xiaobawang.hundouluo.LoginActivity;
import com.xiaobawang.hundouluo.R;
import com.xiaobawang.hundouluo.service.UserService;
import com.xiaobawang.hundouluo.utils.SharedPreferencesUtil;

import java.util.Set;

/**
 * A simple {@link Fragment} subclass.
 */
public class SettingFragment extends Fragment implements View.OnClickListener {

    private RelativeLayout relativeAir, relativeSoil, relativeCarbon, relativeIllumination, relativeAccount;


    public SettingFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View root = inflater.inflate(R.layout.fragment_setting, container, false);

        relativeAir = root.findViewById(R.id.fragment_setting_relative_air);
        relativeSoil = root.findViewById(R.id.fragment_setting_relative_soil);
        relativeCarbon = root.findViewById(R.id.fragment_setting_relative_carbonDioxide);
        relativeIllumination = root.findViewById(R.id.fragment_setting_relative_illumination);
        relativeAccount = root.findViewById(R.id.fragment_setting_relative_account);

        relativeAir.setOnClickListener(this);
        relativeSoil.setOnClickListener(this);
        relativeCarbon.setOnClickListener(this);
        relativeIllumination.setOnClickListener(this);
        relativeAccount.setOnClickListener(this);

        //完成对RePassReceiver广播接收器的注册
        receiver = new RePassReceiver();
        IntentFilter filterRePass = new IntentFilter();
        filterRePass.addAction("com.xiaobawang.hundouluo.receive.rePass");
        SettingFragment.this.getContext().registerReceiver(receiver, filterRePass);

        return root;
    }

    BroadcastReceiver receiver;

    @Override
    public void onDestroy() {
        super.onDestroy();
        SettingFragment.this.getContext().unregisterReceiver(receiver);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fragment_setting_relative_air :
                settingDialog(1);
                break;
            case R.id.fragment_setting_relative_soil :
                settingDialog(2);
                break;
            case R.id.fragment_setting_relative_carbonDioxide :
                settingDialog(3);
                break;
            case R.id.fragment_setting_relative_illumination :
                settingDialog(4);
                break;
            case R.id.fragment_setting_relative_account :
                settingAccount();
                break;

        }
    }

    String fileName;
    private void settingDialog(int location) {
        String title = "";
        String unit = "";
        switch (location) {
            case 1 :
                title = "空气温度报警值设置";
                unit = "℃";
                fileName = "airTemp";
                break;
            case 2 :
                title = "土壤湿度报警值设置";
                unit = "%";
                fileName = "soilHum";
                break;
            case 3 :
                title = "CO₂浓度报警值设置";
                unit = "ppm";
                fileName = "carbonDioxide";
                break;
            case 4 :
                title = "光照强度报警值设置";
                unit = "Klx";
                fileName = "light";
                break;

        }

        TextView tvMinUnit, tvMaxUnit;

        View dialogRoot = LayoutInflater.from(SettingFragment.this.getContext()).inflate(R.layout.dialog_setting, null);
        tvMinUnit = dialogRoot.findViewById(R.id.dialog_setting_tv_minUnit);
        tvMaxUnit = dialogRoot.findViewById(R.id.dialog_setting_tv_maxUnit);
        tvMinUnit.setText(unit);
        tvMaxUnit.setText(unit);
        final EditText etMin = dialogRoot.findViewById(R.id.dialog_setting_et_min);
        final EditText etMax = dialogRoot.findViewById(R.id.dialog_setting_et_max);

        new AlertDialog.Builder(SettingFragment.this.getContext())
                .setTitle(title)
                .setView(dialogRoot)
                .setNegativeButton("取消", null)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String min = etMin.getText().toString().trim();
                        String max = etMax.getText().toString().trim();

                        if(min.length() == 0 || max.length() == 0) {
                            Toast.makeText(SettingFragment.this.getContext(), "请输入最大值和最小值!", Toast.LENGTH_LONG).show();
                            return;
                        } else if(Integer.parseInt(min) > Integer.parseInt(max)){
                            Toast.makeText(SettingFragment.this.getContext(), "请输入正确的最大值和最小值!", Toast.LENGTH_LONG).show();
                            return;
                        }

                        Toast.makeText(SettingFragment.this.getContext(), "设置成功", Toast.LENGTH_LONG).show();

                        //存储数据
                        SharedPreferencesUtil.write(SettingFragment.this.getContext(), fileName, "min", min);
                        SharedPreferencesUtil.write(SettingFragment.this.getContext(), fileName, "max", max);
                    }
                })
                .show();
    }

    private void settingAccount() {

        View accountRoot = LayoutInflater.from(SettingFragment.this.getContext()).inflate(R.layout.account_setting, null);
        final EditText oldPwd = accountRoot.findViewById(R.id.account_setting_et_oldpwd);
        final EditText newPwd = accountRoot.findViewById(R.id.account_setting_et_newpwd);
        final EditText newPwdVerify = accountRoot.findViewById(R.id.account_setting_et_newpwdVerify);
        new AlertDialog.Builder(SettingFragment.this.getContext())
                .setView(accountRoot)
                .setNegativeButton("取消", null)
                .setPositiveButton("确认", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        String newPass = newPwd.getText().toString().trim();
                        String newPassVerify = newPwdVerify.getText().toString().trim();
                        String oldPass = oldPwd.getText().toString().trim();
                        String upwd = SharedPreferencesUtil.read(SettingFragment.this.getContext(), "userInfo", "password");

                        if (newPass.length() == 0 || newPassVerify.length() == 0) {
                            Toast.makeText(SettingFragment.this.getContext(), "请将信息填写完整!", Toast.LENGTH_LONG).show();
                            return;
                        }

                        if (!newPass.equals(newPassVerify)) {
                            Toast.makeText(SettingFragment.this.getContext(), "两次密码不一致!", Toast.LENGTH_LONG).show();
                            return;
                        }

                        if (!oldPass.equals(upwd)) {
                            Toast.makeText(SettingFragment.this.getContext(), "旧密码输入错误!", Toast.LENGTH_LONG).show();
                            return;
                        }

                        Intent sIntent = new Intent(SettingFragment.this.getContext(), UserService.class);
                        sIntent.putExtra("type", "repass");
                        sIntent.putExtra("newpass", newPass);
                        SettingFragment.this.getContext().startService(sIntent);

                    }
                })
                .show();
    }

    class RePassReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String result = intent.getStringExtra("rePassResult");
            if (result.equals("success")) {
                Toast.makeText(SettingFragment.this.getContext(), "修改密码成功!请重新登录", Toast.LENGTH_LONG).show();
                Intent i = new Intent(SettingFragment.this.getContext(), LoginActivity.class);
                startActivity(i);
                SettingFragment.this.getActivity().finish();
            } else {
                Toast.makeText(SettingFragment.this.getContext(), "修改失败!请重新登录后再试", Toast.LENGTH_LONG);
            }
        }
    }

}

